package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardTopUpBean;
import com.ruike.alisurface.bean.OrderPointResultBean;
import com.ruike.alisurface.bean.OrderrBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.http.OtherHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.NumberUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.http.OtherHttp.SEARCH_ORDER_URL;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 扫码页
 */
public class PayForQRCodeActivity extends BaseAty {

    @BindView(R.id.titleBar_titleIco_imgv)
    ImageView titleBarTitleIcoImgv;
    @BindView(R.id.titleBar_appVersion_tv)
    TextView titleBarAppVersionTv;
    @BindView(R.id.titleBar_sn_tv)
    TextView titleBarSnTv;
    @BindView(R.id.titleBar_setting_view)
    View titleBarSettingView;
    @BindView(R.id.titleBar_root_rlayout)
    RelativeLayout titleBarRootRlayout;

    @BindView(R.id.alchatPay_goback_imgv)
    ImageView alchatPayGobackImgv;
    @BindView(R.id.alchat_tuijian)
    TextView alchatTuijian;
    @BindView(R.id.alchat_zxing_code)
    ImageView alchatZxingCode;
    @BindView(R.id.alchat_zxing_price)
    TextView aliZxingPrice;
    @BindView(R.id.alchat_zxing_count_time)
    TextView aliZxingCountTime;

    String OrderNO;
    Bitmap bitmap;
    Timer paytimer;
    TimerTask timerTask;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.alchat_yj)
    TextView alchatYj;
    @BindView(R.id.alchat_yyhje)
    TextView alchatYyhje;
    @BindView(R.id.alchat_yyh_payje)
    TextView alchatYyhPayje;
    @BindView(R.id.pay_type_moryh)
    RelativeLayout payTypeMoryh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layoutYhhd;

    @BindView(R.id.view_zw_hdie)
    View vhide;

    List<CarGoodsBeans> paycarlist;//购物车集合
    double monry = 0.0f;//总金额
    OrderrBean orderrBean;//订单类
    ShopDetailBean shopDetailBean;//商品详情类
    CustomDialog dialog;//弹窗
    AlertDialog alertDialog;//提示框

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_wealchat;
    }

    @Override
    protected void initViews() {
        L.i("扫码支付页==" + this.getClass().getName());
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(500);
        if (paycarlist == null) {
            L.i("查询商品数据异常");
            return;
        }
        L.iTag("下单异常", "获取的购物车列表：" + paycarlist.toString());
        int payPointNumber = 0;
        for (CarGoodsBeans carGoodsBean : paycarlist) {
            payPointNumber += carGoodsBean.getPoint();
        }
        L.iTag("下单异常", "总积分数：" + payPointNumber);
        if (payPointNumber <= 0) {
            showErrorTip("下单商品不得小于1积分");
            startCountdownTimer(3, null, null);
            return;
        }
        showcodeAlt();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(300, aliZxingCountTime, SelectPayTypeActivity.class);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        L.i("requestUrl==" + requestUrl);
        if (requestUrl.endsWith("create") || requestUrl.endsWith("CreateForProduct") ||
                requestUrl.endsWith("create_pay_order") || requestUrl.endsWith("create_pay_order_by_product")) {

            int payCodeExpireTime = 180; // 获取到订单之后的倒计时时间
            if (requestUrl.endsWith("create_pay_order") || requestUrl.endsWith("create_pay_order_by_product")) {

                if (requestJsonStr.contains("silverCardIntegralPrice") && requestJsonStr.contains("goldCardIntegralPrice") && requestJsonStr.contains("platinumCardIntegralPrice")) {
                    try {
                        JSONObject jsonObject = new JSONObject(requestJsonStr);
                        JSONObject dataObject = jsonObject.optJSONObject("data");
                        if (dataObject != null) {
                            int silverCardIntegralPrice = dataObject.optInt("silverCardIntegralPrice");
                            int goldCardIntegralPrice = dataObject.optInt("goldCardIntegralPrice");
                            int platinumCardIntegralPrice = dataObject.optInt("platinumCardIntegralPrice");
                            String pointStr = "";
                            if (silverCardIntegralPrice == goldCardIntegralPrice && goldCardIntegralPrice == platinumCardIntegralPrice) {
                                pointStr = String.format(Locale.ENGLISH, "兑换积分价：%d积分", silverCardIntegralPrice);
                            } else {
                                pointStr = String.format(Locale.ENGLISH, "铂金卡积分价：%d积分\n金 卡 积 分 价：%d积分\n银 卡 积 分 价：%d积分", platinumCardIntegralPrice, goldCardIntegralPrice, silverCardIntegralPrice);
                            }
                            aliZxingPrice.setText(pointStr);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                // 获取商品支付信息
                OrderPointResultBean orderPointResultBean = GsonUtils.json2Model(requestJsonStr, OrderPointResultBean.class);
                OrderPointResultBean.DataBean pointResultDataBean = orderPointResultBean.getData();

                orderrBean = new OrderrBean();

                OrderrBean.DataBean dataBean = new OrderrBean.DataBean();
                dataBean.setUrl(pointResultDataBean.getPreUrl());

                OrderrBean.DataBean.OrderBean orderBean = new OrderrBean.DataBean.OrderBean();
                orderBean.setOrderNo(pointResultDataBean.getOrder_id());
                orderBean.setPay_fee(pointResultDataBean.getTotal_point());

                List<ShopDetailBean.OrderDetailsBean> orderDetails = new ArrayList<>();
                for (OrderPointResultBean.DataBean.DetailListBean detailBean : pointResultDataBean.getDetail_list()) {
                    ShopDetailBean.OrderDetailsBean oldDetailBean = new ShopDetailBean.OrderDetailsBean();
                    oldDetailBean.setSlotIndex(detailBean.getSlotIndex());
                    oldDetailBean.setQuantity(detailBean.getQuantity());
                    oldDetailBean.setSlotTypeId(detailBean.getSlotType());
                    oldDetailBean.setProductName(detailBean.getProduct_name());
                    oldDetailBean.setProductImg(detailBean.getProduct_pic());
                    orderDetails.add(oldDetailBean);
                }
                orderBean.setOrderDetails(orderDetails);

                dataBean.setOrder(orderBean);

                orderrBean.setData(dataBean);

                // 获取传入的倒计时时长
                String payCodeExpireTimeStr = pointResultDataBean.getPayCodeExpireSecondsTime();
                if (BuildConfig.DEBUG) {
                    payCodeExpireTimeStr = "3600";
                }
                payCodeExpireTime = payCodeExpireTimeStr.isEmpty() ? 180 : Integer.parseInt(payCodeExpireTimeStr);
            } else {
                // 获取商品支付信息
                orderrBean = GsonUtils.json2Model(requestJsonStr, OrderrBean.class);
            }

            String zxinurl = orderrBean.getData().getUrl();
            OrderNO = orderrBean.getData().getOrder().getOrderNo();
            bitmap = ZXingUtils.getInstance().createQRImage((zxinurl), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alchatZxingCode.setImageBitmap(bitmap);

            // 要求，订单有效时间为180秒，此处由接口传入
            CountdownTimercancal(); // 先停止BaseAty的倒计时
            startCountdown(payCodeExpireTime); // 开始本界面自己的倒计时

            shopDetailBean = new ShopDetailBean(OrderNO);
            shopDetailBean.setPromotion_fee(orderrBean.getData().getOrder().getPromotion_fee());
            shopDetailBean.setTotal_fee(orderrBean.getData().getOrder().getTotal_fee());
            shopDetailBean.setPay_fee(orderrBean.getData().getOrder().getPay_fee());
            monry = orderrBean.getData().getOrder().getPay_fee();
            L.i("shopDetailBean", shopDetailBean.toString());

            shopDetailBean.setDetailOrderList(orderrBean.getData().getOrder().getOrderDetails());

            try {
                setCanal();
                paytimer = new Timer();
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        OtherHttp.searchOrder(PayForQRCodeActivity.this, OrderNO);
                    }
                };
                paytimer.schedule(timerTask, 10, 3000);
                String acty_config = orderrBean.getData().getOrder().getActivity_config();
                String acty_id = orderrBean.getData().getOrder().getActivity_id();
//                aliZxingPrice.setText(String.format(Locale.ENGLISH, "总支付积分：%d分", (int) monry));
                setHuoDongoing(acty_config, acty_id);
                L.i("acty_id=acty_config===", ShareUtils.getInstance().getString(ShareKey.ACTIVITY_ID, "0"));
            } catch (JSONException e) {
                L.i("wechar===", e.getMessage());
            }

        } else if (SEARCH_ORDER_URL.contentEquals(requestUrl)) {
            JSONObject object = null;
            try {
                object = new JSONObject(requestJsonStr);
                int code = object.optInt("code");
                L.i("getPayResult==" + requestJsonStr);
                if (code == 0) {
                    setCanal();
                    String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
                    L.iTag("支付页==order_code= ", "上次的单号==" + order_code + "==");
                    if (!TextUtils.isEmpty(order_code) && shopDetailBean != null && order_code.equals(shopDetailBean.getOrderId())) {
                        L.iTag("支付页==order_code= ", "这次的单号=="
                                + shopDetailBean.getOrderId() + "==" + "多次出 货，订单号已经出货过 无法再次出货 回到主页面");
                        BackMainUtils.setActivity(this);
                        finish();
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("pay_type", "wechat");
                    bundle.putSerializable("orderBeanData", shopDetailBean);
                    startActivity(PayShowShopActivity.class, bundle);
                    finish();
                } else {
                    L.i("getPayResult" + "==等待支付=");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    CountDownTimer countDownTimer;

    /**
     * 开启倒计时
     *
     * @param payCodeExpireTime 倒计时时长
     */
    private void startCountdown(int payCodeExpireTime) {
        cancelCountdown();
        countDownTimer = new CountDownTimer(payCodeExpireTime * 1000, 1000) {
            @Override
            public void onTick(long l) {
                aliZxingCountTime.setText(String.format(Locale.ENGLISH, "%ds", l / 1000 + 1));
                if (l <= 2000) {
                    L.e("订单超时，取消订单：" + orderrBean.getData().getOrder().getOrderNo());
                    showErrorTip("订单超时...");
                    // 取消订单
                    OtherHttp.cancelOrder(orderrBean.getData().getOrder().getOrderNo(), PayForQRCodeActivity.this);
                }
            }

            @Override
            public void onFinish() {
                startCountdownTimer(0, null, SelectPayTypeActivity.class);
            }
        };
        countDownTimer.start();
    }

    /**
     * 结束倒计时
     */
    private void cancelCountdown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (SEARCH_ORDER_URL.contentEquals(requestUrl)) {
            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
            return;
        }
        if (requestUrl.endsWith("create") || requestUrl.endsWith("CreateForProduct") ||
                requestUrl.endsWith("create_pay_order") || requestUrl.endsWith("create_pay_order_by_product")) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
        }
    }

    @OnClick({R.id.alchatPay_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.alchatPay_goback_imgv:
                String tip = "支付过程中请勿关闭该扫码支付页面，否则即使支付成功也无法出货！！！\r\n\r\n" +
                        "如想返回其它页面则点击确认，否则点击取消等待支付完成后出货！！！";
                gobackTip(tip);
                break;
        }
    }

    public void gobackTip(String tip) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new CustomDialog.Builder(this).setTitle("温馨提示")
                .setMessage(tip).setTouchOutsideCloseDialog(false)
                .setPositiveButton("确认", (dialog, which) -> {
                    sendOrderStatus(0);
                    startCountdown(1);
                    startCountdownTimer(1, null, SelectPayTypeActivity.class);
                    try {
                        String orderNo = orderrBean.getData().getOrder().getOrderNo();
                        OtherHttp.cancelOrder(orderNo, PayForQRCodeActivity.this);
                    } catch (NullPointerException e) {
                        L.e("订单号为空，取消订单接口暂时不上报。");
                    }
                })
                .setNegativeButton("取消", null).create();
        dialog.show();
    }


    /**
     * 生成二维码提示框
     */
    private void showcodeAlt() {
        try {
            showProgressDialog("正在生成二维码加载数据，请稍后......", false);
            if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
                L.i("按货道展示上传信息");
                getPayinfoCode();
            } else {
                L.i("按商品类型展示上传信息");
                getPayTypeinfoCode();
            }
        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    /**
     * 按货道下单
     */
    public void getPayinfoCode() {
        OtherHttp.createOrderBySlot(paycarlist, this);
    }

    /**
     * 按类型下单
     */
    public void getPayTypeinfoCode() {
        OtherHttp.createOrderByProduct(paycarlist, this);
    }

    public void setCanal() {
        if (timerTask != null) {
            L.i("==setCanal=取消计时=timerTask=" + timerTask);
            timerTask.cancel();
            timerTask = null;
        }
        if (paytimer != null) {
            L.i("==setCanal=取消计时=paytimer" + paytimer);
            paytimer.cancel();
            paytimer = null;
        }
    }

    /**
     * 活动显示数据判断
     */
    public void setHuoDongoing(String acty_config, String acty_id) throws JSONException {
        if (TextUtils.isEmpty(acty_id)) {
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "0");
            return;
        }
        L.i("acty_id=acty_config====", orderrBean.getData().getOrder().getActivity_id());
        if (orderrBean.getData().getOrder().getActivity_id().equals("1")) { // 转盘
            vhide.setVisibility(View.VISIBLE);
            layoutYhhd.setVisibility(View.GONE);
            ShareUtils.getInstance().putString(ShareKey.ACTIVITY_ID, "1");
            return;
        }
        JSONObject Js = new JSONObject(acty_config);
        if (TextUtils.isEmpty(acty_config)) {
            return;
        }

    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("计时结束") && event.getMessage().equals("查询订单倒计时结束")) {
//                EventBus.getDefault().post(new MsgEventBus("计时结束", "查询订单倒计时结束"));
            sendOrderStatus(1);
        }
    }

    /**
     * 上传订单是否超时
     */
    public void sendOrderStatus(int sign_order_state) {
        if (!TextUtils.isEmpty(OrderNO)) {
            MchApiHttp.sendSign_order(OrderNO, sign_order_state, PayForQRCodeActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("==onDestroy==");
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        cancelCountdown();

        if (bitmap != null) {
            alchatZxingCode.setImageBitmap(null);
            bitmap.recycle();
            bitmap = null;
        }

        if (alertDialog != null) {
            alertDialog.dismiss();
            alertDialog = null;
        }
        setCanal();
    }

}
